class TaskManager {
    constructor() {
        this.todos = [];
        this.currentCategory = 'today';
        this.currentView = 'list'; // 添加视图状态：'list' 或 'kanban'
    }

    async loadTodos() {
        try {
            this.todos = await ipcRenderer.invoke('get-todos');
            // 修复没有优先级的任务
            this.todos.forEach(todo => {
                if (!todo.priority) {
                    todo.priority = 'medium';
                }
            });
            // 保存修复后的数据
            await this.saveTodos();
        } catch (error) {
            console.error('加载任务失败:', error);
            this.todos = [];
        }
    }

    async saveTodos() {
        try {
            await ipcRenderer.invoke('save-todos', this.todos);
        } catch (error) {
            console.error('保存任务失败:', error);
        }
    }

    addTask(text, pomodoros = 0, dueDate = null, priority = 'medium', description = '') {
        const task = {
            id: String(Date.now()),
            text: text,
            description: description || '',
            completed: false,
            status: 'todo',
            category: this.currentCategory,
            priority: priority || 'medium',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            estimatedTime: pomodoros > 0 ? pomodoros * 25 : 0,
            pomodoros: pomodoros,
            dueDate: dueDate ? dueDate.toISOString() : null
        };

        this.todos.unshift(task);
        return task;
    }

    toggleTask(id) {
        const task = this.todos.find(t => t.id === id);
        if (task) {
            task.completed = !task.completed;
            task.updatedAt = new Date().toISOString();
            if (task.completed) {
                task.completedAt = new Date().toISOString();
                task.status = 'completed';
            } else {
                delete task.completedAt;
                task.status = 'todo';
            }
            return task;
        }
        return null;
    }

    deleteTask(id) {
        const index = this.todos.findIndex(t => t.id === id);
        if (index !== -1) {
            const deletedTask = this.todos.splice(index, 1)[0];
            
            // 记录删除操作到本地存储
            const deletedTasks = JSON.parse(localStorage.getItem('deletedTasks') || '[]');
            deletedTasks.push({
                id: deletedTask.id,
                deletedAt: new Date().toISOString()
            });
            localStorage.setItem('deletedTasks', JSON.stringify(deletedTasks));
            
            return deletedTask;
        }
        return null;
    }

    getFilteredTodos() {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
        const weekEnd = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000);

        let filtered = [];
        
        switch (this.currentCategory) {
            case 'today':
                filtered = this.todos.filter(todo => {
                    const todoDate = new Date(todo.createdAt);
                    return todoDate >= today && todoDate < tomorrow && !todo.completed;
                });
                break;
            case 'tomorrow':
                filtered = this.todos.filter(todo => {
                    const todoDate = new Date(todo.createdAt);
                    return todoDate >= tomorrow && todoDate < new Date(tomorrow.getTime() + 24 * 60 * 60 * 1000) && !todo.completed;
                });
                break;
            case 'week':
                filtered = this.todos.filter(todo => {
                    const todoDate = new Date(todo.createdAt);
                    return todoDate >= today && todoDate < weekEnd && !todo.completed;
                });
                break;
            case 'planned':
                filtered = this.todos.filter(todo => !todo.completed);
                break;
            case 'completed':
                filtered = this.todos.filter(todo => todo.completed);
                break;
            case 'high-priority':
                filtered = this.todos.filter(todo => todo.priority === 'high' && !todo.completed);
                break;
            case 'medium-priority':
                filtered = this.todos.filter(todo => todo.priority === 'medium' && !todo.completed);
                break;
            case 'low-priority':
                filtered = this.todos.filter(todo => todo.priority === 'low' && !todo.completed);
                break;
            case 'tasks':
            default:
                filtered = this.todos;
                break;
        }
        
        // 根据设置进行优先级排序
        const settings = this.getSettings();
        if (settings.sortByPriority) {
            filtered.sort((a, b) => {
                const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
                return priorityOrder[b.priority || 'medium'] - priorityOrder[a.priority || 'medium'];
            });
        }
        
        return filtered;
    }

    getCountForCategory(category) {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
        const weekEnd = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000);

        switch (category) {
            case 'today':
                return this.todos.filter(todo => {
                    const todoDate = new Date(todo.createdAt);
                    return todoDate >= today && todoDate < tomorrow && !todo.completed;
                }).length;
            case 'tomorrow':
                return this.todos.filter(todo => {
                    const todoDate = new Date(todo.createdAt);
                    return todoDate >= tomorrow && todoDate < new Date(tomorrow.getTime() + 24 * 60 * 60 * 1000) && !todo.completed;
                }).length;
            case 'week':
                return this.todos.filter(todo => {
                    const todoDate = new Date(todo.createdAt);
                    return todoDate >= today && todoDate < weekEnd && !todo.completed;
                }).length;
            case 'planned':
                return this.todos.filter(todo => !todo.completed).length;
            case 'completed':
                return this.todos.filter(todo => todo.completed).length;
            case 'high-priority':
                return this.todos.filter(todo => todo.priority === 'high' && !todo.completed).length;
            case 'medium-priority':
                return this.todos.filter(todo => todo.priority === 'medium' && !todo.completed).length;
            case 'low-priority':
                return this.todos.filter(todo => todo.priority === 'low' && !todo.completed).length;
            case 'tasks':
            default:
                return this.todos.length;
        }
    }

    switchCategory(category) {
        this.currentCategory = category;
    }

    updateTask(id, updates) {
        const task = this.todos.find(t => t.id === id);
        if (task) {
            // 更新任务属性
            if (updates.text !== undefined) task.text = updates.text;
            if (updates.pomodoros !== undefined) {
                task.pomodoros = updates.pomodoros;
                task.estimatedTime = updates.pomodoros * 25;
            }
            if (updates.dueDate !== undefined) {
                task.dueDate = updates.dueDate ? updates.dueDate.toISOString() : null;
            }
            if (updates.priority !== undefined) {
                task.priority = updates.priority;
            }
            
            // 更新修改时间
            task.updatedAt = new Date().toISOString();
            
            return task;
        }
        return null;
    }

    // 新增：获取设置
    getSettings() {
        const defaultSettings = {
            showPriorityInSidebar: true,
            sortByPriority: false,
            highPriorityFirst: false,
            mediumPriorityFirst: false,
            lowPriorityFirst: false
        };
        
        try {
            const saved = localStorage.getItem('todoSettings');
            return saved ? { ...defaultSettings, ...JSON.parse(saved) } : defaultSettings;
        } catch {
            return defaultSettings;
        }
    }

    // 新增：保存设置
    saveSettings(settings) {
        try {
            localStorage.setItem('todoSettings', JSON.stringify(settings));
        } catch (error) {
            console.error('保存设置失败:', error);
        }
    }

    getTaskById(id) {
        return this.todos.find(t => t.id === id);
    }

    // 新增：更新任务状态
    updateTaskStatus(id, status) {
        const task = this.todos.find(t => t.id === id);
        if (task) {
            task.status = status;
            if (status === 'completed') {
                task.completed = true;
                task.completedAt = new Date().toISOString();
            } else {
                task.completed = false;
                delete task.completedAt;
            }
            return task;
        }
        return null;
    }

    // 新增：按状态获取任务
    getTasksByStatus(status) {
        const filteredTodos = this.getFilteredTodos();
        return filteredTodos.filter(todo => {
            if (status === 'todo') {
                return !todo.completed && (!todo.status || todo.status === 'todo');
            } else if (status === 'inprogress') {
                return !todo.completed && todo.status === 'inprogress';
            } else if (status === 'completed') {
                return todo.completed || todo.status === 'completed';
            }
            return false;
        });
    }

    // 新增：切换视图
    switchView(view) {
        this.currentView = view;
    }
}

// 删除这行：module.exports = TaskManager;